package login_register

import (
	"errors"
	"gorm.io/gorm"
	"internal/api/types"
	"internal/store"
	"internal/store/mysql"
	"internal/util"
	"time"
)

func UserRegister(req *types.LoginReq) (value types.UserInfo, err error) {
	data := &store.FkUser{UserName: req.Username}
	// 先判断用户名和密码是否存在
	err = mysql.GetConn().First(data, "f_name=?", data.UserName).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			data.UserId = GetAccountDA()
			data.Password = HashPassword(req.Password)
			data.LoginTime = time.Now()
			data.RegisterTime = time.Now()
			data.EditTime = time.Now()
			err := mysql.GetConn().Create(data).Error
			if err != nil {
				util.LogSrv.Error("fk_user insert into failed!, err= %v", err)
				return value, nil
			}
			value = types.UserInfo{
				UserId:       data.UserId,
				UserName:     data.UserName,
				Password:     data.Password,
				LoginTime:    data.LoginTime.Format("2006-01-02 15:04:05"),
				RegisterTime: data.RegisterTime.Format("2006-01-02 15:04:05"),
				EditTime:     data.EditTime.Format("2006-01-02 15:04:05"),
			}
		} else {
			util.LogSrv.Error("fk_user query f_name and f_password, err= %v", err)
			return value, err
		}
	} else {
		return value, errors.New("account already exists")
	}
	return value, nil
}
